package com.eleadin.ruleengine.service;

import com.eleadin.ruleengine.service.vo.user.*;
import com.eleadin.ruleengine.utils.BeanUtils;
import com.eleadin.ruleengine.utils.CryptoUtil;
import com.eleadin.ruleengine.context.FeignContextHolder;
import com.eleadin.ruleengine.jwt.SecurityConstant;
import com.eleadin.ruleengine.service.base.BaseService;
import com.eleadin.ruleengine.dao.entity.UserDO;
import com.eleadin.ruleengine.dao.mapper.UserMapper;
import com.eleadin.ruleengine.utils.Result;
import com.eleadin.ruleengine.token.TokenHelper;
import com.eleadin.ruleengine.token.TokenModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.util.List;

/**
 * @ClassName UserServiceImpl
 */
@Slf4j
@Service
public class UserService extends BaseService {
    @Autowired
    private TokenHelper tokenHelper;
    @Autowired
    private UserMapper userMapper;

    @Value("${user.default-password:123456}")
    private String defaultPassword;

    public Result<String> login(UserLoginReqVO reqVO) throws Exception {
        // 自我校验登录逻辑
        UserDO userDO = userMapper.selectByLoginName(reqVO.getUserName());
        if (null == userDO) {
            return Result.fail("用户信息不存在");
        }
        String cypherPassword = cryptoPassword(reqVO.getPassword(), userDO.getUserId());
        if (!cypherPassword.equals(userDO.getPassword())) {
            log.error("登录密码错误！");
            return Result.fail("登录密码错误！");
        }
        TokenModel model = tokenHelper.create(userDO.getUserId(), userDO.getUserName());
        return Result.ok(model.getToken());
    }

    //加密
    private String cryptoPassword(String text, String salt) throws Exception {
        String orginalText = text + "_" + salt;
        try {
            byte[] cypherBytes = CryptoUtil.encryptMD5(orginalText.getBytes());
            String cypherText = new BigInteger(cypherBytes).toString(16);
            return cypherText;
        } catch (Exception e) {
            log.error("加密用户密码时异常:" + e.getMessage());
            throw new Exception(e.getMessage());
        }
    }

    public Result logout(HttpServletRequest request) {
        Object userId = request.getAttribute(SecurityConstant.CURRENT_USER_ID);
        if (null == userId) {
            return Result.ok();
        }
        return tokenHelper.delete(String.valueOf(userId)) ? Result.ok() : Result.fail();
    }

    public Result add(AddUserReqVO reqVO) throws Exception {
        UserDO userDO = userMapper.selectByLoginName(reqVO.getUserName());
        if (null != userDO) {
            return Result.fail("用户名称已存在");
        }

        UserDO addUserDO = BeanUtils.convert(reqVO, UserDO.class);
        addUserDO.setUserId(nextIdString());
        String password = StringUtils.isBlank(addUserDO.getPassword()) ? defaultPassword : addUserDO.getPassword();
        String cryptoPassword = this.cryptoPassword(password, addUserDO.getUserId());
        addUserDO.setPassword(cryptoPassword);
        userMapper.insert(addUserDO);
        return Result.ok();
    }

    public Result checkMobile(String mobile) {
        Boolean exists = userMapper.exists(mobile, null);
        return exists ? Result.ok() : Result.fail(String.format("登陆名%s不存在，请确认！", mobile));
    }

    public Result resetPassword(ResetPasswordReqVO reqVO) throws Exception {
        UserDO userDO = userMapper.selectByLoginName(reqVO.getUserName());
        if (null == userDO) {
            return Result.fail("用户信息不存在！");
        }
        String cryptoPassword = this.cryptoPassword(reqVO.getPassword(), userDO.getUserId());
        return userMapper.updatePassword(cryptoPassword, userDO.getUserId()) > 0 ? Result.ok() : Result.fail("修改密码失败");
    }

    public Result update(UpdateUserReqVO reqVO) throws Exception {
        UserDO userDO = BeanUtils.convert(reqVO, UserDO.class);
        if (StringUtils.isNotBlank(reqVO.getPassword())) {
            String password = cryptoPassword(reqVO.getPassword(), userDO.getUserId());
            userDO.setPassword(password);
        }
        if (StringUtils.isNotBlank(reqVO.getMobile())) {
            Boolean exists = userMapper.exists(reqVO.getMobile(), reqVO.getUserId());
            if (exists) {
                return Result.fail("手机号已存在！");
            }
        }
        userMapper.updateByPrimaryKeySelective(userDO);
        return Result.ok();
    }

    public Result<SelfInfoVO> getSelfInfo() {
        String userId = FeignContextHolder.getUserId();
        UserDO userDO = userMapper.selectByPrimaryKey(userId);
        return Result.ok(BeanUtils.convert(userDO, SelfInfoVO.class));
    }

    public Result delete(List<Long> idList) {
        return null;
    }
}
